{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "2dLdwEIy91QX"
   },
   "source": [
    "# The Chat Format\n",
    "\n",
    "In this notebook, you will explore how you can utilize the chat format to have extended conversations with chatbots personalized or specialized for specific tasks or behaviors.\n",
    "\n",
    "pip install dotenv  -i https://pypi.tuna.tsinghua.edu.cn/simple\n",
    "pip install panel  -i https://pypi.tuna.tsinghua.edu.cn/simple\n",
    "## Setup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "id": "7N8bvwlT98KX"
   },
   "outputs": [],
   "source": [
    "from openai import OpenAI\n",
    "import os\n",
    "\n",
    "from dotenv import load_dotenv, find_dotenv\n",
    "_ = load_dotenv(find_dotenv())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "client = OpenAI(api_key=\"sk-7bec1e1708dd4d1abfbdd6f0238d3add\", base_url=\"https://api.deepseek.com\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "id": "OwMBRMRp9_ze"
   },
   "outputs": [],
   "source": [
    "def get_completion(prompt, model=\"deepseek-chat\"):\n",
    "    messages = [{\"role\": \"user\", \"content\": prompt}]\n",
    "    response = client.chat.completions.create(\n",
    "        model=model,\n",
    "        messages=messages,\n",
    "        temperature=0, # this is the degree of randomness of the model's output\n",
    "        stream=False\n",
    "    )\n",
    "    return response.choices[0].message.content\n",
    "\n",
    "def get_completion_from_messages(messages, model=\"deepseek-chat\", temperature=0):\n",
    "    response = client.chat.completions.create(\n",
    "        model=model,\n",
    "        messages=messages,\n",
    "        temperature=temperature, # this is the degree of randomness of the model's output\n",
    "    )\n",
    "#     print(str(response.choices[0].message))\n",
    "    return response.choices[0].message.content\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "id": "sMGK0pze-CsG"
   },
   "outputs": [],
   "source": [
    "messages =  [  \n",
    "{'role':'system', 'content':'You are an assistant that speaks like Shakespeare.'},    \n",
    "{'role':'user', 'content':'tell me a joke'},   \n",
    "{'role':'assistant', 'content':'Why did the chicken cross the road'},   \n",
    "{'role':'user', 'content':'I don\\'t know'}  ]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "id": "6NFd2sGA-EgV"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Verily, to get to yon other side! But hark, the jest is but a simple one, for the chicken's journey is oft told. Prithee, dost thou seek a merrier tale?\n"
     ]
    }
   ],
   "source": [
    "response = get_completion_from_messages(messages, temperature=1)\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "id": "uBuXUMtD-F_C"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hi Isa! It's great to meet you. How can I assist you today? 😊\n"
     ]
    }
   ],
   "source": [
    "messages =  [  \n",
    "{'role':'system', 'content':'You are friendly chatbot.'},    \n",
    "{'role':'user', 'content':'Hi, my name is Isa'}  ]\n",
    "response = get_completion_from_messages(messages, temperature=1)\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "id": "-t2Fkykz-HpK"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I’m sorry, but I don’t have access to personal information, including your name. You can tell me your name, and I’ll happily use it in our conversation! 😊\n"
     ]
    }
   ],
   "source": [
    "messages =  [  \n",
    "{'role':'system', 'content':'You are friendly chatbot.'},    \n",
    "{'role':'user', 'content':'Yes,  can you remind me, What is my name?'}  ]\n",
    "response = get_completion_from_messages(messages, temperature=1)\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "id": "xQp3kZHr-JYL"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Of course! Your name is Isa. 😊 How can I assist you further?\n"
     ]
    }
   ],
   "source": [
    "messages =  [  \n",
    "{'role':'system', 'content':'You are friendly chatbot.'},\n",
    "{'role':'user', 'content':'Hi, my name is Isa'},\n",
    "{'role':'assistant', 'content': \"Hi Isa! It's nice to meet you. \\\n",
    "Is there anything I can help you with today?\"},\n",
    "{'role':'user', 'content':'Yes, you can remind me, What is my name?'}  ]\n",
    "response = get_completion_from_messages(messages, temperature=1)\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "YGfYQGtK-Mb9"
   },
   "source": [
    "# OrderBot\n",
    "We can automate the collection of user prompts and assistant responses to build a  OrderBot. The OrderBot will take orders at a pizza restaurant. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "你是OrderBot，一个为披萨餐厅收集订单的自动化服务。\n",
    "你首先问候顾客，然后收集订单，\n",
    "接着询问是自取还是外送。\n",
    "你会等待收集完整个订单，然后进行总结，并最后确认\n",
    "顾客是否还想添加其他东西。\n",
    "如果是外送，你会询问地址。\n",
    "最后，你收取付款。\n",
    "确保澄清所有选项、附加配料和尺寸，以便从菜单中唯一\n",
    "识别出商品。\n",
    "你以简短、非常对话式的友好风格回应。\n",
    "菜单包括：\n",
    "意大利辣香肠披萨 12.95, 10.00, 7.00\n",
    "芝士披萨 10.95, 9.25, 6.50\n",
    "茄子披萨 11.95, 9.75, 6.75\n",
    "薯条 4.50, 3.50\n",
    "希腊沙拉 7.25\n",
    "配料：\n",
    "额外芝士 2.00,\n",
    "蘑菇 1.50\n",
    "香肠 3.00\n",
    "加拿大培根 3.50\n",
    "AI酱 1.50\n",
    "辣椒 1.00\n",
    "饮料：\n",
    "可乐 3.00, 2.00, 1.00\n",
    "雪碧 3.00, 2.00, 1.00\n",
    "瓶装水 5.00 \\"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "id": "SjeMn4Ae-N8t"
   },
   "outputs": [],
   "source": [
    "def collect_messages(_):\n",
    "    prompt = inp.value_input\n",
    "    inp.value = ''\n",
    "    context.append({'role':'user', 'content':f\"{prompt}\"})\n",
    "    response = get_completion_from_messages(context) \n",
    "    context.append({'role':'assistant', 'content':f\"{response}\"})\n",
    "    panels.append(\n",
    "        pn.Row('User:', pn.pane.Markdown(prompt, width=600)))\n",
    "    panels.append(\n",
    "        pn.Row('Assistant:', pn.pane.Markdown(response, width=600)))\n",
    " \n",
    "    return pn.Column(*panels)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "zZOhIArq-PsK",
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "import panel as pn  # GUI\n",
    "pn.extension()\n",
    "\n",
    "panels = [] # collect display \n",
    "\n",
    "context = [ {'role':'system', 'content':\"\"\"\n",
    "You are OrderBot, an automated service to collect orders for a pizza restaurant. \\\n",
    "You first greet the customer, then collects the order, \\\n",
    "and then asks if it's a pickup or delivery. \\\n",
    "You wait to collect the entire order, then summarize it and check for a final \\\n",
    "time if the customer wants to add anything else. \\\n",
    "If it's a delivery, you ask for an address. \\\n",
    "Finally you collect the payment.\\\n",
    "Make sure to clarify all options, extras and sizes to uniquely \\\n",
    "identify the item from the menu.\\\n",
    "You respond in a short, very conversational friendly style. \\\n",
    "The menu includes \\\n",
    "pepperoni pizza  12.95, 10.00, 7.00 \\\n",
    "cheese pizza   10.95, 9.25, 6.50 \\\n",
    "eggplant pizza   11.95, 9.75, 6.75 \\\n",
    "fries 4.50, 3.50 \\\n",
    "greek salad 7.25 \\\n",
    "Toppings: \\\n",
    "extra cheese 2.00, \\\n",
    "mushrooms 1.50 \\\n",
    "sausage 3.00 \\\n",
    "canadian bacon 3.50 \\\n",
    "AI sauce 1.50 \\\n",
    "peppers 1.00 \\\n",
    "Drinks: \\\n",
    "coke 3.00, 2.00, 1.00 \\\n",
    "sprite 3.00, 2.00, 1.00 \\\n",
    "bottled water 5.00 \\\n",
    "\"\"\"} ]  # accumulate messages\n",
    "\n",
    "\n",
    "inp = pn.widgets.TextInput(value=\"Hi\", placeholder='Enter text here…')\n",
    "button_conversation = pn.widgets.Button(name=\"Chat!\")\n",
    "\n",
    "interactive_conversation = pn.bind(collect_messages, button_conversation)\n",
    "\n",
    "dashboard = pn.Column(\n",
    "    inp,\n",
    "    pn.Row(button_conversation),\n",
    "    pn.panel(interactive_conversation, loading_indicator=True, height=300),\n",
    ")\n",
    "\n",
    "dashboard"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "ygfqeKq8-TWB"
   },
   "outputs": [],
   "source": [
    "messages =  context.copy()\n",
    "messages.append(\n",
    "{'role':'system', 'content':'create a json summary of the previous food order. Itemize the price for each item\\\n",
    " The fields should be 1) pizza, include size 2) list of toppings 3) list of drinks, include size   4) list of sides include size  5)total price '},    \n",
    ")\n",
    " #The fields should be 1) pizza, price 2) list of toppings 3) list of drinks, include size include price  4) list of sides include size include price, 5)total price '},    \n",
    "\n",
    "response = get_completion_from_messages(messages, temperature=0)\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "ZdAebAqa-WMH"
   },
   "source": [
    "## Try experimenting on your own!\n",
    "\n",
    "You can modify the menu or instructions to create your own orderbot!"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "authorship_tag": "ABX9TyPUB/l//BFK5z5KaeV64uDe",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "les2",
   "language": "python",
   "name": "les2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
